// 引入express
import express from 'express';
const mysql = require('mysql');
//实例化express
const app = express()
// 创建数据库连接
const connection = mysql.createConnection({
  host: '43.138.105.103',
  user: 'conistydy_user',
  password: '123456',
  database: 'conistydy_user'
});
setInterval(checkForNewRecords, 5000); // 每5秒检查一次

function checkForNewRecords() {
  console.log('执行了');
  const query = 'SELECT * FROM test_menu ORDER BY id DESC LIMIT 1';
  connection.query(query, (error, results, fields) => {
    if (error) throw error;
    // 假设表中有id字段，并且每条记录的id是递增的
    const latestId = results[0].id;
    if (latestId > lastCheckedId) { // lastCheckedId是全局变量或存储在文件中的上一次检查的id
      // 新数据被检测到
      onNewRecord(results); // onNewRecord是当检测到新记录时要执行的方法
      lastCheckedId = latestId; // 更新lastCheckedId
    }
  });
}

function onNewRecord(record) {
  // 处理新记录的逻辑
  console.log('New record:', record);
}
//创建接口get请求
app.get('/', function (req, res) {
  this.checkForNewRecords()
  res.send('你好呀 !Hello World!')
})
app.post('/api', function (req, res) {
  res.send('你好呀 !Hello World!post')
})
//创建服务器
app.listen(8828, () => {
  console.log('server is running on port 8828')
})